<template>
  <div class="remote-transfer-container">
    <el-card class="header-card">
      <template #header>
        <div class="card-header">
          <h2>
            <el-icon><Upload /></el-icon>
            远程传输任务下发
          </h2>
          <p class="subtitle">选择在线客户端，浏览文件并创建传输任务</p>
        </div>
      </template>
    </el-card>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 左侧：客户端列表 -->
      <el-col :span="8">
        <el-card class="client-list-card">
          <template #header>
            <div class="card-header">
              <span>在线客户端 ({{ onlineClients.length }})</span>
              <el-button
                size="small"
                @click="loadOnlineClients"
                :loading="loading.clients"
                :icon="Refresh"
              >
                刷新
              </el-button>
            </div>
          </template>

          <div v-loading="loading.clients" class="client-list">
            <div
              v-for="client in onlineClients"
              :key="client.client_id"
              class="client-item"
              :class="{ 
                active: selectedClient?.client_id === client.client_id,
                'no-websocket': !client.hasWebSocket
              }"
              @click="selectClient(client)"
            >
              <div class="client-info">
                <div class="client-name">
                  <el-icon class="platform-icon">
                    <Monitor v-if="client.platform === 'darwin'" />
                    <Platform v-else />
                  </el-icon>
                  {{ client.hostname || client.client_id }}
                  <el-tag 
                    v-if="!client.hasWebSocket" 
                    type="warning" 
                    size="small"
                    style="margin-left: 8px;"
                  >
                    无WebSocket
                  </el-tag>
                </div>
                <div class="client-meta">
                  <el-tag size="small">{{ client.os_type }}</el-tag>
                  <span class="client-user">{{ client.username }}</span>
                </div>
                <div class="client-ip">{{ client.ip_address }}</div>
              </div>
            </div>

            <el-empty
              v-if="!loading.clients && onlineClients.length === 0"
              description="暂无在线客户端"
              :image-size="80"
            />
          </div>
        </el-card>
      </el-col>

      <!-- 中间：文件浏览器 -->
      <el-col :span="16">
        <el-card class="file-browser-card" v-if="selectedClient">
          <template #header>
            <div class="card-header">
              <span>客户端文件浏览</span>
              <el-button
                size="small"
                @click="loadClientDirectory(currentPath)"
                :loading="loading.directory"
                :icon="Refresh"
              >
                刷新
              </el-button>
            </div>
          </template>

          <!-- 路径导航 -->
          <div class="path-bar">
            <div class="path-controls">
              <!-- Windows 磁盘选择器 -->
              <el-select
                v-if="isWindows"
                v-model="currentDrive"
                @change="changeDrive"
                placeholder="选择磁盘"
                style="width: 100px; margin-right: 10px;"
                size="small"
              >
                <el-option
                  v-for="drive in availableDrives"
                  :key="drive"
                  :label="drive"
                  :value="drive"
                />
              </el-select>
              
              <el-breadcrumb separator="/">
                <el-breadcrumb-item @click="navigateToPath(isWindows ? currentDrive : '/')">
                  <el-icon><HomeFilled /></el-icon>
                  {{ isWindows ? currentDrive : '根目录' }}
                </el-breadcrumb-item>
                <el-breadcrumb-item
                  v-for="(part, index) in pathParts"
                  :key="index"
                  @click="navigateToPath(getPathUpTo(index))"
                >
                  {{ part }}
                </el-breadcrumb-item>
              </el-breadcrumb>
            </div>
          </div>

          <!-- 文件列表 -->
          <div v-loading="loading.directory" class="file-list">
            <el-table
              :data="files"
              @selection-change="handleSelectionChange"
              height="400"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column label="名称" min-width="200">
                <template #default="{ row }">
                  <div
                    class="file-name"
                    @dblclick="row.isDirectory && navigateToPath(row.path)"
                  >
                    <el-icon class="file-icon">
                      <Folder v-if="row.isDirectory" />
                      <Document v-else />
                    </el-icon>
                    {{ row.name }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="大小" width="120">
                <template #default="{ row }">
                  {{ row.isDirectory ? '-' : formatSize(row.size) }}
                </template>
              </el-table-column>
              <el-table-column label="修改时间" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.modified) }}
                </template>
              </el-table-column>
            </el-table>

            <el-empty
              v-if="!loading.directory && files.length === 0"
              description="目录为空"
              :image-size="80"
            />
          </div>

          <!-- 操作栏 -->
          <div class="action-bar" v-if="selectedFiles.length > 0">
            <div class="selection-info">
              已选择 {{ selectedFiles.length }} 个文件/文件夹
            </div>
            <el-button
              type="primary"
              @click="showTaskDialog('upload')"
              :icon="Upload"
            >
              上传到服务器
            </el-button>
          </div>
        </el-card>

        <el-empty
          v-else
          description="请先选择一个在线客户端"
          :image-size="120"
        />
      </el-col>
    </el-row>

    <!-- 创建任务对话框 -->
    <el-dialog
      v-model="taskDialog.visible"
      title="上传到服务器"
      width="600px"
    >
      <el-form :model="taskForm" label-width="120px">
        <el-form-item label="客户端">
          <el-input :value="selectedClient?.hostname" disabled />
        </el-form-item>
        <el-form-item label="源路径">
          <el-input :value="currentPath" disabled />
        </el-form-item>
        <el-form-item label="目标路径">
          <el-input
            v-model="taskForm.targetPath"
            placeholder="请输入目标路径"
          />
        </el-form-item>
        <el-form-item label="选中文件">
          <div class="selected-files-list">
            <el-tag
              v-for="file in selectedFiles"
              :key="file.name"
              style="margin: 5px;"
            >
              {{ file.name }}
            </el-tag>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="taskDialog.visible = false">取消</el-button>
        <el-button
          type="primary"
          @click="dispatchTask"
          :loading="loading.dispatch"
        >
          创建任务
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import {
  Upload,
  Refresh,
  Monitor,
  Platform,
  HomeFilled,
  Folder,
  Document
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/api'

// 状态
const onlineClients = ref([])
const selectedClient = ref(null)
const currentPath = ref('/')
const files = ref([])
const selectedFiles = ref([])

// Windows 磁盘相关
const isWindows = ref(false)
const currentDrive = ref('C:')
const availableDrives = ref(['C:', 'D:', 'E:', 'F:', 'G:', 'H:'])

const loading = reactive({
  clients: false,
  directory: false,
  dispatch: false
})

const taskDialog = reactive({
  visible: false,
  type: ''
})

const taskForm = reactive({
  targetPath: ''
})

// 计算属性
const pathParts = computed(() => {
  let path = currentPath.value
  
  // Windows 路径处理
  if (isWindows.value && path) {
    // 移除驱动器号（如 C:）
    if (path.match(/^[A-Z]:/)) {
      path = path.substring(2)
    }
    // 分割路径（支持 \ 和 /）
    return path.split(/[/\\]/).filter(p => p)
  }
  
  // Unix 路径处理
  return path.split('/').filter(p => p)
})

// 方法
const loadOnlineClients = async () => {
  loading.clients = true
  try {
    const response = await api.get('/api/clients/online')
    if (response.data.success) {
      onlineClients.value = response.data.data
      ElMessage.success(`加载成功，${onlineClients.value.length} 个在线客户端`)
    }
  } catch (error) {
    console.error('加载客户端列表失败:', error)
  } finally {
    loading.clients = false
  }
}

const selectClient = (client) => {
  // 检查客户端是否有 WebSocket 连接
  if (!client.hasWebSocket) {
    ElMessage.warning('该客户端未建立WebSocket连接，无法执行远程操作')
    return
  }
  
  selectedClient.value = client
  files.value = []
  selectedFiles.value = []
  
  // 检测操作系统
  const osType = client.os_type?.toLowerCase() || client.platform?.toLowerCase() || ''
  isWindows.value = osType.includes('win') || osType.includes('windows')
  
  if (isWindows.value) {
    // Windows 系统：默认从 C: 开始
    currentDrive.value = 'C:'
    currentPath.value = 'C:\\'
    loadClientDirectory('C:\\')
  } else {
    // Unix/Linux/Mac 系统：从根目录开始
    currentPath.value = '/'
    loadClientDirectory('/')
  }
}

// 切换驱动器
const changeDrive = (drive) => {
  currentDrive.value = drive
  const drivePath = drive + '\\'
  loadClientDirectory(drivePath)
}

const loadClientDirectory = async (path) => {
  if (!selectedClient.value) return

  loading.directory = true
  try {
    const response = await api.get(
      `/api/clients/${selectedClient.value.client_id}/directory`,
      { params: { path } }
    )
    if (response.data.success) {
      currentPath.value = response.data.data.path
      files.value = response.data.data.files || []
      
      // Windows：从路径中提取当前驱动器
      if (isWindows.value && currentPath.value) {
        const driveMatch = currentPath.value.match(/^([A-Z]:)/)
        if (driveMatch) {
          currentDrive.value = driveMatch[1]
        }
      }
    }
  } catch (error) {
    console.error('加载目录失败:', error)
    ElMessage.error(error.response?.data?.message || '加载目录失败')
  } finally {
    loading.directory = false
  }
}

const navigateToPath = (path) => {
  loadClientDirectory(path)
}

const getPathUpTo = (index) => {
  const parts = pathParts.value.slice(0, index + 1)
  
  if (isWindows.value) {
    // Windows 路径
    return currentDrive.value + '\\' + parts.join('\\')
  } else {
    // Unix 路径
    return '/' + parts.join('/')
  }
}

const handleSelectionChange = (selection) => {
  selectedFiles.value = selection
}

const showTaskDialog = (type) => {
  taskDialog.type = type
  taskDialog.visible = true
  // 设置默认目标路径为上传目录
  taskForm.targetPath = '/uploads'
}

const dispatchTask = async () => {
  if (!taskForm.targetPath) {
    ElMessage.warning('请输入目标路径')
    return
  }

  if (selectedFiles.value.length === 0) {
    ElMessage.warning('请选择文件')
    return
  }

  loading.dispatch = true
  try {
    const response = await api.post('/api/clients/dispatch-task', {
      clientId: selectedClient.value.client_id,
      type: 'upload',
      sourcePath: currentPath.value,
      targetPath: taskForm.targetPath,
      files: selectedFiles.value.map(f => ({
        name: f.name,
        size: f.size,
        isDirectory: f.isDirectory
      }))
    })

    if (response.data.success) {
      ElMessage.success('任务已下发！')
      taskDialog.visible = false
      selectedFiles.value = []
    }
  } catch (error) {
    console.error('下发任务失败:', error)
  } finally {
    loading.dispatch = false
  }
}

const formatSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
}

const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

// 初始化
loadOnlineClients()
</script>

<style scoped>
.remote-transfer-container {
  padding: 20px;
}

.header-card .card-header h2 {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-card .subtitle {
  margin: 10px 0 0 0;
  color: #909399;
  font-size: 14px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.client-list-card,
.file-browser-card {
  height: 600px;
  overflow: hidden;
}

.client-list {
  height: 500px;
  overflow-y: auto;
}

.client-item {
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s;
}

.client-item:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.client-item.active {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.client-item.no-websocket {
  opacity: 0.6;
  cursor: not-allowed;
}

.client-item.no-websocket:hover {
  border-color: #e4e7ed;
  background-color: #f5f7fa;
}

.client-name {
  font-size: 16px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.platform-icon {
  color: #409eff;
}

.client-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 5px;
}

.client-user {
  color: #606266;
  font-size: 13px;
}

.client-ip {
  color: #909399;
  font-size: 12px;
}

.path-bar {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 15px;
}

.path-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.file-list {
  min-height: 400px;
}

.file-name {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.file-name:hover {
  color: #409eff;
}

.file-icon {
  color: #909399;
}

.action-bar {
  margin-top: 15px;
  padding: 15px;
  background-color: #f0f9ff;
  border-radius: 6px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selection-info {
  color: #409eff;
  font-weight: 500;
}

.selected-files-list {
  max-height: 200px;
  overflow-y: auto;
}
</style>
